const { mysqlHandle, mysqlHandleCurry, setResponse } = require('../utils');
const { connect } = require('../connectDatabase');

/* eslint-disable */
const addBookmarkCategorySql = 'insert into bookmarkcategory (name) values (?)';
const deleteBookmarkCategorySql = 'delete from bookmarkcategory where id in (?)';
const updateBookmarkCategorySql = 'update bookmarkcategory set name=? where id=?';
const getBookmarkCategorySql = 'select * from bookmarkcategory';

const addBookmarkUrlsSql =
  'INSERT INTO bookmarkurls (category_id, name, url, favicon) VALUES (?, ?, ?, ?)';
const deleteBookmarkUrlsSql = 'delete from bookmarkurls where id in (?)';
const updateBookmarkUrlsSql =
  'update bookmarkurls set category_id=?,name=?,url=?,favicon=? where id=?';
const getBookmarkUrlsSql = 'select * from bookmarkurls';
/* eslint-enable */

function transformData(categories, items) {
  // 构建一个映射对象，便于根据id查找类别名称
  const categoryIdToNameMap = categories.reduce((acc, category) => {
    acc[category.id] = category.name;
    return acc;
  }, {});

  // 使用reduce和find来根据category_id找到对应的类别名称，然后构造urls数组
  const transformedData = items.reduce((result, item) => {
    const categoryName = categoryIdToNameMap[item.category_id];
    if (!result[categoryName]) {
      result[categoryName] = { categoryName, categoryId: item.category_id, urls: [] };
    }
    result[categoryName].urls.push({
      id: item.id,
      url: item.url,
      name: item.name,
      favicon: item.favicon,
    });
    return result;
  }, {});

  // 将reduce结果转换为数组形式返回
  return Object.values(transformedData);
}

const getBookmarks = async (req, res) => {
  let connection;
  const { categoryName } = req.query;
  try {
    connection = await connect();
    const excute = mysqlHandleCurry(mysqlHandle)(connection);
    const bookmarkCategory = await excute(getBookmarkCategorySql);
    const bookmarkUrls = await excute(getBookmarkUrlsSql);
    let bookmarks = transformData(bookmarkCategory, bookmarkUrls);
    const item = bookmarkCategory.find((i) => i.name === '娱乐夹');
    if (categoryName === '娱乐夹') {
      if (item) {
        bookmarks = bookmarks.filter((i) => i.categoryId === item.id);
      } else {
        bookmarks = [];
      }
    } else {
      if (item) {
        bookmarks = bookmarks.filter((i) => i.categoryId !== item.id);
      }
    }
    const response = setResponse({
      code: 'SUCCESS',
      data: bookmarks,
      message: '',
      success: true,
    });
    res.status(200).json(response);
  } catch (error) {
    res.status(500).send(error);
  } finally {
    if (connection) {
      connection.end();
    }
  }
};

const addBookmark = async (req, res) => {
  let connection;
  try {
    const { categoryName, urlName, url, favicon } = req.body;
    connection = await connect();
    const excute = mysqlHandleCurry(mysqlHandle)(connection);
    const bookmarkCategory = await excute(getBookmarkCategorySql);
    let exists = bookmarkCategory.find((item) => item.name === categoryName);
    if (exists) {
      console.log('🚀 ~ app.post ~ exists:', exists);
      // 直接往bookmarUrls表里插入数据
      const result = await mysqlHandle(
        connection,
        addBookmarkUrlsSql,
        exists.id,
        urlName,
        url,
        favicon,
      );
      if (!result.error) {
        const response = setResponse({
          code: 'SUCCESS',
          data: {},
          message: '',
          success: true,
        });
        res.status(200).json(response);
      } else {
        const response = setResponse({
          code: 'FAILED',
          data: {},
          message: result.error,
          success: false,
        });
        res.status(200).json(response);
      }
    } else {
      // 先往bookmarkCategory里插入数据，再往bookmarkUrls里插入数据
      const { insertId } = await mysqlHandle(
        connection,
        'INSERT INTO bookmarkCategory (name) VALUES (?)',
        categoryName,
      );
      console.log('🚀 ~ app.post ~ insertId:', insertId);
      const result = await mysqlHandle(
        connection,
        addBookmarkUrlsSql,
        insertId,
        url,
        urlName,
        favicon,
      );
      if (!result.error) {
        const response = setResponse({
          code: 'SUCCESS',
          data: {},
          message: '',
          success: true,
        });
        res.status(200).json(response);
      } else {
        const response = setResponse({
          code: 'FAILED',
          data: {},
          message: result.error,
          success: false,
        });
        res.status(200).json(response);
      }
    }
  } catch (error) {
    console.log('🚀 ~ app.post ~ error:', error);
    const response = setResponse({
      code: 'FAILED',
      data: {},
      message: error,
      success: false,
    });
    res.status(500).json(response);
  } finally {
    if (connection) {
      connection.end();
    }
  }
};

const updateBookmark = async (req, res) => {
  let connection;
  try {
    const { id, categoryName, urlName, url, favicon } = req.body;
    connection = await connect();
    const excute = mysqlHandleCurry(mysqlHandle)(connection);
    const bookmarkCategory = await excute(getBookmarkCategorySql);
    let exists = bookmarkCategory.find((item) => item.name === categoryName);
    if (exists) {
      console.log('🚀 ~ app.post ~ exists:', exists);
      // 直接往bookmarUrls表里插入数据
      const result = await excute(updateBookmarkUrlsSql, exists.id, urlName, url, favicon, id);
      if (!result.error) {
        const response = setResponse({
          code: 'SUCCESS',
          data: {},
          message: '',
          success: true,
        });
        res.status(200).json(response);
      } else {
        const response = setResponse({
          code: 'FAILED',
          data: {},
          message: result.error,
          success: false,
        });
        res.status(200).json(response);
      }
    } else {
      // 先往bookmarkCategory里插入数据，再往bookmarkUrls里插入数据
      const { insertId } = excute(addBookmarkUrlsSql, categoryName);
      console.log('🚀 ~ app.post ~ insertId:', insertId);
      const result = await excute(updateBookmarkUrlsSql, exists.id, urlName, url, favicon, id);
      if (!result.error) {
        const response = setResponse({
          code: 'SUCCESS',
          data: {},
          message: '',
          success: true,
        });
        res.status(200).json(response);
      } else {
        const response = setResponse({
          code: 'FAILED',
          data: {},
          message: result.error,
          success: false,
        });
        res.status(200).json(response);
      }
    }
  } catch (error) {
    console.log('🚀 ~ app.post ~ error:', error);
    const response = setResponse({
      code: 'FAILED',
      data: {},
      message: error,
      success: false,
    });
    res.status(500).json(response);
  } finally {
    if (connection) {
      connection.end();
    }
  }
};
const deleteBookmark = async (req, res) => {
  let connection;
  try {
    connection = await connect();
    const excute = mysqlHandleCurry(mysqlHandle)(connection);
    await excute(deleteBookmarkUrlsSql, req.params.id);
    const response = setResponse({
      code: 'SUCCESS',
      data: {},
      message: '',
      success: true,
    });
    res.status(200).json(response);
  } catch (error) {
    const response = setResponse({
      code: 'FAILED',
      data: {},
      message: error,
      success: false,
    });
    res.status(500).json(response);
  } finally {
    if (connection) {
      connection.end();
    }
  }
};

module.exports = {
  getBookmarks,
  addBookmark,
  updateBookmark,
  deleteBookmark,
};
